fpath = '1-0.bin'; %'balloons.png'; 

inputvideo = 'V3V100013_010.crop.avi'; %'video.avi';

VISUALIZE = 0;  %0 : no visualization validate output file, 1: visualize matlab output

nr_frame = 128; %256;
nc_frame = 128; %256;
nr = 128; %256; %128; %256
nc = 128; %256; %128; %256;
NUM_FRAMES = 200; %42; %201
CHIPS_PER_FRAME = 1; %53; %4; %53; %1;

Nc = 3; %1; % num of center channels

% bin_dat_bar = 1;     %0 : dat file (ascii), 1 : binary file

output_nr = 16; %8; %16; % size of output saliency
output_nc = 16; %8; %16;
%% for comparing hardware result
if(nr_frame==128)
    error_threshold = 1e-2;
else
    error_threshold = 1e-3;
end
result_flag = 1;

bin_dat_bar = 1;     %0 : dat file (ascii), 1 : binary file
% res_fname_0 = '1-o_BAK.bin';
% res_fname_1 = '2-o_BAK.bin';
if (bin_dat_bar == 1)
%     outfilepath=  'R:\fourier\MSPark\Saliency API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6\'; %'results\saliency_retina_dma\'; 

%     outfilepath = 'R:\fourier\MSPark\err_output_concerns\test_result_6\';
%     outfilepath = 'R:\fourier\MSPark\Saliency API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_256_0519bs\';
%      outfilepath = 'R:\fourier\MSPark\Saliency API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_basler_0519bs\';
%     outfilepath = 'R:\fourier\MSPark\Saliency API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_vivid512_0519bs\';
%     outfilepath = 'R:\fourier\MSPark\HRL object percept detection API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_vivid512_0527bs\';
%     outfilepath = 'R:\fourier\MSPark\HRL object percept detection API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_vivid512_0524bs_w_newMain_memfix\';
%     outfilepath = 'R:\fourier\MSPark\HRL object percept detection API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6\';
    outfilepath = 'R:\fourier\MSPark\object_detection_multi_API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6\';
else
    outfilepath = 'results\saliency_retina\'; %'results\beta_CFIOM_6cs_256\';
end

input_BINfile = 1; % if input is to be read from binary file
infile_path = outfilepath;

% logfile = 'R:\fourier\MSPark\err_output_concerns\Matlab_Verification\output512x512_1.log';
logfile = 'R:\fourier\MSPark\err_output_concerns\Matlab_Verification\output.log';

if(VISUALIZE == 1)  %if visualization enabled
    scrsz= get(0,'ScreenSize');
%     h = figure('position',[200 scrsz(4)/3 scrsz(3)/2 scrsz(4)/3]);
    h = figure('position',[10 scrsz(4)/3 scrsz(3) scrsz(4)/3]);
       
    p0 = subplot(1,3,1);
    axis equal
    %%set(gca,'nextplot', 'replacechildren');
    p1 = subplot(1,3,2);
    axis equal    
    p2 = subplot(1,3,3);
    axis equal    

%     p0 = subplot(1,2,1);
%     axis equal
%     p2 = subplot(1,2,2);
%     axis equal       

end

logfile_id = fopen(logfile,'w+');   %open the log file
qout = quantizer('ufixed', [24,20]);  %output data rep
qin = quantizer('ufixed',[8,0]); % for r, g, b values

im_curr = zeros(nr,nc,3);
im_prev = zeros(nr,nc,3);

  mov = aviread(inputvideo) ; 
  
 out_mov(1:NUM_FRAMES) = struct('cdata', [],'colormap', []);
                        
   for i = 1:NUM_FRAMES  %size(mov,2) %will go to number of frames 
       for cp = 1:CHIPS_PER_FRAME
  
        j = cp-1;
       if(input_BINfile == 1)    %binary file
%% current input
%            out_filename=strcat(outfilepath,num2str(i),'-','c','.','bin');     %check file name i-o-BAK.bin exixts
%             in_filename=strcat(infile_path,'3C', '36F', '-','cSourceBuffer','.bin');     %check file name i-o-BAK.bin exixts
            in_filename=strcat(infile_path, num2str(j), 'c', num2str(i), 'f', '2id', '-cSourceBuffer','.bin');
            check_file =0;
            while (check_file ~= 2)
                check_file= exist (in_filename, 'file');
            end
            file_id = fopen(in_filename,'r');
            Bdec=dec2hex(fread(file_id,inf,'uint8'));
            array_out= hex2num(qin,Bdec); 
            fclose(file_id);
            array_out = array_out(17: end);
            im1 = reshape(array_out, 4, nr*nc);
            r = im1(3, :)';
            g = im1(2, :)';
            b = im1(1, :)';
            r1 = reshape(r, nr, nc)';
            g1 = reshape(g, nr, nc)';
            b1 = reshape(b, nr, nc)';
            im_curr(:,:,1) = r1;
            im_curr(:,:,2) = g1;
            im_curr(:,:,3) = b1;
%             im_curr = reshape(array_out, nc, nr)';
%% previous input            
%            out_filename=strcat(outfilepath,num2str(i),'-','p','.','bin');            
%            in_filename=strcat(infile_path,'3C', '36F', '-','pSourceBuffer','.bin');     %check file name i-o-BAK.bin exixts
           in_filename=strcat(infile_path, num2str(j), 'c', num2str(i), 'f', '2id', '-pSourceBuffer','.bin');
            check_file =0;
            while (check_file ~= 2)
                check_file= exist (in_filename, 'file');
            end
            file_id = fopen(in_filename,'r');
            Bdec=dec2hex(fread(file_id,inf,'uint8'));
            array_out= hex2num(qin,Bdec); 
            fclose(file_id);
            array_out = array_out(17: end);
            im1 = reshape(array_out, 4, nr*nc);
            r = im1(3, :)';
            g = im1(2, :)';
            b = im1(1, :)';
            r1 = reshape(r, nr, nc)';
            g1 = reshape(g, nr, nc)';
            b1 = reshape(b, nr, nc)';
            im_prev(:,:,1) = r1;
            im_prev(:,:,2) = g1;
            im_prev(:,:,3) = b1;
%             im_prev = reshape(array_out, nc, nr)';
       else
%             if(i == 1)
%                 im_prev = zeros(nr,nc,3); %(size(mov(1,i).cdata));
%             else
%                 im_prev = frame;
%             end
%             frame = mov(1,i).cdata;
%             im_curr = frame;
            
            im_prev = mov(1,i-1).cdata;
            im_curr = mov(1,i).cdata;
       end
       
       %% Create dat files for the input chips
%        if (j == 16)
%         rgb2dat_n('0C152F-c.dat', im_curr, 2);
%         rgb2dat_n('0C152F-p.dat', im_prev, 2);
%        end

       
  
%     [Sal, iSal, cSal, oSal, mSal, fSal] = saliency_hw_sim(im_prev, im_curr, nr, nc, Nc, i+1);
    [Sal, iSal, cSal, oSal, mSal, fSal] = saliency_hw_sim128(im_prev, im_curr, nr, nc, Nc, i+1);       

    if(bin_dat_bar == 1)    %binary file
%          out_filename=strcat(outfilepath,num2str(i  ),'-','o_BAK','.','bin');     %check file name i-o-BAK.bin exixts
        out_filename=strcat(outfilepath, num2str(j), 'c', num2str(i), 'f', '2id', '-TargetBuffer','.bin');
%          out_filename=strcat(outfilepath,'3C36F','-','TargetBuffer','.bin');     %check file name i-o-BAK.bin exixts            

        check_file =0;
        while (check_file ~= 2)
            check_file= exist (out_filename, 'file');
        end
        file_id = fopen(out_filename,'r');
        Bdec=dec2hex(fread(file_id,inf,'uint32'));
        array_out= hex2num(qout,Bdec); 
        fclose(file_id);
        result_hw = reshape(array_out, output_nc, output_nr)';
    elseif(bin_dat_bar == 0)  %dat file
        out_filename=strcat(outfilepath,num2str(i),'-','o_BAK','.','dat');     %check file name i-o-BAK.bin exixts
        check_file =0;
        while (check_file ~= 2)
            check_file= exist (out_filename, 'file');
        end
        array_out = dat2array(out_filename, output_nr*output_nc, qout);          
        result_hw = reshape(array_out, output_nc, output_nr)';
    end

    if(VISUALIZE)
        axes(p0)
%         imagesc(imresize(im_curr, [nr,nc]));
        imagesc(im_curr);
%         title (['Input Frame  ']);
        title (['Input Frame  ', num2str(i)]);

        axes(p1)
        imagesc((Sal/5));        %Visualize REF output
        title (['Ref Saliency  ', num2str(i)]);

%         axes(p2)
%         imagesc(imresize(Sal/5,[nr,nc]));   %Visualize HARDWARE output
% %         title (['FPGA Saliency  ']);
%         title (['FPGA Saliency  ', num2str(i)]); 
        
        pause(0.01) %0.25
  %      out_mov(i)= getframe(h);
    end
    
    abs_error = abs((Sal/5) - (result_hw/5));
    max_error = max(max(abs_error));
    avg_error = mean(mean(abs_error));       

    error_flag = abs_error > error_threshold;
    num_error = sum(sum(error_flag));
    error_flag = error_flag * 1111;

    minsal = min(min(Sal/5));
    maxsal_r = max(max(Sal/5));
    err_r = maxsal_r > 0.99;
    err_r = err_r * 1111;
    
    maxsal_h = max(max(result_hw/5));
    err_h = maxsal_h > 0.99;
    err_h = err_h * 1111;


    fprintf(logfile_id,'Chip %d, Frame %d -- Max255_REF = %d, Max255_HW = %d, Max_Ref = %f, Max_hw = %f, num error = %d, max error = %E, avg error = %E\n', j, i, err_r, err_h, maxsal_r, maxsal_h, num_error, max_error, avg_error);
   end
    
   end
   
%close the log file
 fclose(logfile_id);

 %% Make movie 
%  close(h);
 %movie2avi(out_mov, 'saliency_6cs_256_SX475.avi', 'compression', 'None');
 
        
